<?php
/**
 * Created by PhpStorm.
 * User: mww
 * Date: 2018/12/17
 * Time: 16:08
 */
namespace app\api\controller;
use think\Db;
class Sae extends Base
{
    /**
     * 异地登录验证
     * @return string|void
     */
    public function _initialize()
    {
        extract(input());
        if($user_id != 0){
            $auth = $this->checkAll($user_id,$time,$value,$reqKey);
            if($auth == 112){
                echo json(['status'=>301,'msg'=>$this->otherLogin]);
                exit;
            }elseif($auth == 110){
                echo json(['status' => 302, 'msg' => $this->frost]);
                exit;
            }elseif($auth == 1103){
                echo json(['status' => 303, 'msg' => $this->del]);
                exit;
            }
        }

    }


    /**
     * 上报sae：saeAdd
     */
    public function saeAdd(){
        extract(input());
        $user = $this->getUserInfo($user_id,'user_type,user_auth,user_hospital,user_sheng,user_shi',2);
        $today = date('Y-m-d H:i:s');
        //只给我产品id就行了，公司id来查
        $cp = Db::table('up_company_product')->where('cp_id',$cp_id)
            ->field('cp_c_id,cp_charge_uid')->find();
        $user_type = $user['user_type'];
        $realdata = $this->productRealCharger($cp_id,$user_id,$cp['cp_c_id']);
        $cp['cp_charge_uid'] = '';
        if($realdata){
            $cp['cp_charge_uid'] = $realdata['user_id'];
        }
        if(!$cp['cp_charge_uid']){
            return json(['status'=>100,'msg'=>'此产品暂无负责人，请联系管理员']);
        }
        $data = [
            'sae_send_uid' => $user_id,
            'sae_name' => $sae_name,
            'sae_sex' => $sae_sex, //直接传男女即可
            'sae_birthday' => $sae_birthday,
            'sae_phone' => $sae_phone,
            'sae_sick' => $sae_sick, //第一步结束
            'sae_cp_id' => $cp_id,
            'sae_c_id' => $cp['cp_c_id'],
            'sae_spec' => $sae_spec,
            'sae_use_date' => $sae_use_date,
            'sae_use_many' => $sae_use_many,
            'sae_other_drug' => $sae_other_drug, //第二步结束
            'sae_event_name' => $sae_event_name,
            'sae_happend_date' => $sae_happend_date,
            'sae_result' => $sae_result,
            'sae_desc' => $sae_desc,
            'sae_imgs' => trim($sae_imgs,','),
            'sae_radio' => $sae_radio,
            'sae_radio_second' => $sae_radio_second,
            'sae_video' => $sae_video,
            'sae_video_second' => $sae_video_second,
            'sae_time' => $today,
            'sae_update' => $today
        ];
        if($user_type == 1){
            $data['sae_get_uid'] = $cp['cp_charge_uid'];
            $data['sae_all_ids'] = ',' . $cp['cp_charge_uid'] . ',';
        }else{
            $data['sae_get_uid'] = 0;
            $data['sae_all_ids'] = ',' . $user_id . ',';
//            $data['sae_all_ids'] = ',0,';
        }
        Db::startTrans();
        try{
            $res = Db::table('up_sae')->insertGetId($data);
            $reply = [
                'sr_sae_id' => $res,
                'sr_user_id' => $user_id,
                'sr_time' => $today,
                'sr_show' => 2,
                'sr_read_uid' => ',0,',
                'sr_del_uid' => ',0,',
            ];
            Db::table('up_sae_reply')->insertGetId($reply);
            Db::commit();
            if($data['sae_get_uid'] > 0){
                try {
                    $this->Jpush(1, $data['sae_get_uid'], '你有一条新的SAE报告，去处理', ['id' => $res,'n_type' => 3]);
                } catch (\Exception $e) {
                }
            }

            return json(['status'=>200,'msg'=>'提交成功']);
        }catch (\Exception $e) {
            Db::rollback();
            return json(['status'=>100,'msg'=>'提交失败，请稍后重试']);
        }
    }
    /**
     * 医药圈上报时获取数据：saeGetCp
     * 先给产品(公司信息也在里面)
     */
    public function saeGetCp(){
        extract(input());
        $user = $this->getUserInfo($user_id,'user_type,user_hospital',2);
        $where = [
            'cp_status' => 1
        ];
        if($user['user_type'] != 1){
            $where['cp_c_id'] = $user['user_hospital'];
        }
        if(isset($keyword) && $keyword){
            $where['cp_name'] = ['like','%' . $keyword . '%'];
        }
        $data = Db::table('up_company_product p')
            ->join('up_company c','p.cp_c_id=c.c_id','LEFT')
            ->where($where)
            ->order('cp_update DESC')
            ->field('cp_id,cp_name,c_name')
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }

    /**
     * 我的报告记录
     * comefrom:1是我收到的 2是我发布的
     */
    public function mySae(){
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type == 1){
            $where = [
                'sae_send_uid' => $user_id
            ];
        }else{
            $where = [
                'sae_all_ids' => ['like','%,' . $user_id . ',%']
            ];
            if($comefrom == 1){
                $where['sae_send_uid'] = ['<>',$user_id];
            }else{
                $where['sae_send_uid'] = $user_id;
            }
        }
        if(isset($c_id) && $c_id){ //从筛选出过来的
            $where['sae_c_id'] = $c_id;
        }
        $subQuery = Db::table('up_sae s')
            ->join('up_company_product cp','s.sae_cp_id=cp.cp_id','LEFT')
            ->join('up_company c','s.sae_c_id=c.c_id','LEFT')
            ->join('up_u_user u','cp.cp_charge_uid=u.user_id','LEFT')
            ->where($where)
            ->order('sae_update desc')
            ->field('s.sae_id,s.sae_cp_id,s.sae_update,cp_id,cp_name,cp_thumb,c_id,c_name,c_logo,user_id,user_username,user_image')
            ->buildSql();
        $data = Db::table($subQuery."a")
            ->group('sae_cp_id')
            ->order('sae_update desc')
            ->page($page,10)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我的报告记录之筛选之获取我报告过包含的企业列表
     */
    public function mySaeSelect(){
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type == 1){
            $where = [
                'sae_send_uid' => $user_id
            ];
        }else{
            $where = [
                'sae_all_ids' => ['like','%,' . $user_id . ',%']
            ];
        }
        $data = Db::table('up_sae s')
            ->join('up_company c','s.sae_c_id=c.c_id','LEFT')
            ->where($where)
            ->field('s.sae_id,c_id,c_name,c_logo')
            ->group('sae_c_id')
            ->order('sae_update desc')
//            ->page($page,20)
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 此报告下的用户列表（只有业务员有）
     */
    public function saeCpUsers(){
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type == 1){
            return json(['status'=>100,'msg'=>'无此操作']);
        }
        $where = [
            'sae_all_ids' => ['like','%,' . $user_id . ',%'],
            'sae_cp_id' => $cp_id
        ];
        $subQuery = Db::table('up_sae s')
            ->join('up_u_user u','s.sae_send_uid=u.user_id','LEFT')
            ->where($where)
            ->order('sae_update desc')
            ->field('s.sae_id,s.sae_send_uid,s.sae_update,user_id,user_username,user_image')
            ->buildSql();
        $data = Db::table($subQuery."a")
            ->group('sae_send_uid')
            ->order('sae_update desc')
            ->page($page,20)
            ->select();
        if($data){
            foreach ($data as $k => $v){
                //提问的人是是否是好友
                $like = Db::table('up_friend')
                    ->where('friend_user_id', $user_id)
                    ->where('friend_other_user', $v['user_id'])
                    ->find();
                $data[$k]['friend'] = 0; //不是好友
                if($like){
                    $data[$k]['friend'] = 1; //是好友
                }
            }
        }
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 报告某用户提问记录
     * sae_id：报告id即可
     */
    public function saeUserRec()
    {
        extract(input());
        $sae = Db::table('up_sae')
            ->where('sae_id', $sae_id)
            ->field('sae_send_uid,sae_cp_id')
            ->find();
        $data = Db::table('up_sae')
            ->where('sae_send_uid',$sae['sae_send_uid'])
            ->where('sae_cp_id',$sae['sae_cp_id'])
            ->order('sae_update desc')
            ->page($page,20)
            ->field('sae_id,sae_update,sae_submit,sae_answer')
            ->select();
        return json(['status'=>200,'msg'=>$data]);
    }
    /**
     * 某报告详情
     * sae_id：报告id即可
     * 如果是医生，找负责人，
     * 如果是业务员找发起人，我发起的不能跟自己聊，不管是发给谁，都是给后台了，所以这里统一不能聊
     */
    public function saeInfo()
    {
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type == 1){
            $field = 'cp_charge_uid';
            $field_f = 'cp';
        }else{
            $field = 'sae_send_uid';
            $field_f = 's';
        }
        $data = Db::table('up_sae s')
            ->join('up_company_product cp','s.sae_cp_id=cp.cp_id','LEFT')
            ->join('up_company c','s.sae_c_id=c.c_id','LEFT')
            ->join('up_u_user u',"{$field_f}.{$field}=u.user_id",'LEFT')
            ->where('sae_id', $sae_id)
            ->field('s.*,cp_name,c_name,user_id,user_username,user_image')
            ->find();
        if($data['sae_imgs']){
            $data['sae_imgs'] = explode(',',$data['sae_imgs']);
        }else{
            $data['sae_imgs'] = [];
        }
        $data['sae_sick'] = explode('|||||',$data['sae_sick']);
        $data['sae_other_drug'] = explode('|||||',$data['sae_other_drug']);
        $data['sae_result'] = explode('|||||',$data['sae_result']);
        $data['sae_desc'] = explode('|||||',$data['sae_desc']);
        //有没有转让
        if($data['sae_zhuan'] == 2){
            $uids = trim($data['sae_zhuan_ids'],',');
            $zhuan_names = Db::table('up_u_user')
                ->where('user_id', 'in',$uids)
                ->column('user_username');
            $data['zhuan_names'] = implode($zhuan_names,'、');
        }
        //回复
        $field = 'sr.*,user_id,user_username,user_image,user_type';
        $reply = Db::table('up_sae_reply sr')
            ->join('up_u_user u1','sr.sr_user_id=u1.user_id','LEFT')
            ->where('sr_sae_id',$sae_id)
            ->where('sr_show',1)
            ->where('sr_fid',0)
            ->order('sr_time desc')
            ->field($field)
            ->select();
        if($reply){
            foreach ($reply as $k2 => $v2){
                if($v2['sr_imgs']){
                    $reply[$k2]['sr_imgs'] = explode(',',$v2['sr_imgs']);
                }else{
                    $reply[$k2]['sr_imgs'] = [];
                }
                $reply_son = Db::table('up_sae_reply sr')
                    ->join('up_u_user u1','sr.sr_user_id=u1.user_id','LEFT')
                    ->where('sr_fid',$v2['sr_id'])
                    ->order('sr_time desc')
                    ->field($field)
                    ->select();
                if($reply_son){
                    foreach ($reply_son as $k3 => $v3) {
                        if ($v3['sr_imgs']) {
                            $reply_son[$k3]['sr_imgs'] = explode(',', $v3['sr_imgs']);
                        } else {
                            $reply_son[$k3]['sr_imgs'] = [];
                        }
                    }
                }
                $reply[$k2]['son'] = $reply_son;
            }
        }

        return json(['status'=>200,'msg'=>$data,'reply'=>$reply]);
    }
    /**
     * 报告补充：
     * sae_id：报告id
     */
    public function saeContinue(){
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type != 1){
            return json(['status'=>100,'msg'=>'您不能补充！']);
        }else{
            $sae = Db::table('up_sae')->where('sae_id',$sae_id)
                ->field('sae_sick,sae_other_drug,sae_result,sae_desc')
                ->find();
            $today = date('Y-m-d H:i:s');
            $data = [
                'sae_update' => $today
            ];
            $content = '';
            if(isset($sae_sick) && $sae_sick){
                $data['sae_sick'] = $sae['sae_sick'] . '|||||' . $sae_sick;
                $content = $sae_sick;
            }
            if(isset($sae_other_drug) && $sae_other_drug){
                $data['sae_other_drug'] = $sae['sae_other_drug'] . '|||||' . $sae_other_drug;
                $content = $sae_other_drug;
            }
            if(isset($sae_result) && $sae_result){
                $data['sae_result'] = $sae['sae_result'] . '|||||' . $sae_result;
                $content = $sae_result;
            }
            if(isset($sae_desc) && $sae_desc){
                $data['sae_desc'] = $sae['sae_desc'] . '|||||' . $sae_desc;
                $content = $sae_desc;
            }
            Db::startTrans();
            try{
                Db::table('up_sae')->where('sae_id',$sae_id)->update($data);
                $reply = [
                    'sr_sae_id' => $sae_id,
                    'sr_content' => $content,
                    'sr_user_id' => $user_id,
                    'sr_time' => $today,
                    'sr_show' => 3,
                    'sr_read_uid' => ',0,',
                    'sr_del_uid' => ',0,',
                ];
                Db::table('up_sae_reply')->insertGetId($reply);
                Db::commit();
                return json(['status'=>200,'msg'=>'提交成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json(['status'=>100,'msg'=>'提交失败，请稍后重试']);
            }
        }
    }
    /**
     * 直接新建新的一级回复：
     * sae_id：报告id
     */
    public function saeComment(){
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type == 1){
            return json(['status'=>100,'msg'=>'您只能回复，不能发起！']);
        }else{
            $today = date('Y-m-d H:i:s');
            $insert = [
                'sr_sae_id' => $sae_id,
                'sr_content' => $content,
                'sr_imgs' => trim($imgs,','),
                'sr_user_id' => $user_id,
                'sr_read_uid' => ',0,',
                'sr_del_uid' => ',0,',
                'sr_time' => $today
            ];
            $res = Db::table('up_sae_reply')->insert($insert);
            if($res){
                Db::table('up_sae')->where('sae_id',$sae_id)->update([
                    'sae_answer' => 2,
                    'sae_answer_time' => $today
                ]);
                try {
                    $whoQ = Db::table('up_sae')->where('sae_id',$sae_id)
                        ->field('sae_send_uid,sae_get_uid,sae_all_ids')->find();
                    if($whoQ['sae_get_uid'] > 0){
                        $whoStr = $whoQ['sae_send_uid'] . $whoQ['sae_all_ids'];
                        $whoStr = trim($whoStr,',');
                        $whoArr = explode(',',$whoStr);
                        $list = array_diff($whoArr, array($user_id));
                        $this->Jpush(1, $list, '你有一条新的SAE报告回复消息，去处理', ['id' => $sae_id,'n_type' => 3]);
                    }
                } catch (\Exception $e) {
                }
                return json(['status'=>200,'msg'=>'操作成功']);
            }else{
                return json(['status'=>100,'msg'=>'操作失败，请刷新重试']);
            }
        }
    }
    /**
     * 直接回复：
     * sr_id：回复的id
     */
    public function saeCommentReply(){
        extract(input());
        $ff = Db::table('up_sae_reply')->where('sr_id',$sr_id)->field('sr_sae_id,sr_fid')->find();
        $today = date('Y-m-d H:i:s');
        $insert = [
            'sr_sae_id' => $ff['sr_sae_id'],
            'sr_content' => $content,
            'sr_imgs' => trim($imgs,','),
            'sr_user_id' => $user_id,
            'sr_fid' => $sr_id,
            'sr_read_uid' => ',0,',
            'sr_del_uid' => ',0,',
            'sr_time' => $today
        ];
        if($ff['sr_fid'] > 0){
            $insert['sr_fid'] = $ff['sr_fid'];
        }
        $res = Db::table('up_sae_reply')->insert($insert);
        if($res){
            $user_type = $this->getUserInfo($user_id,'user_type');
            $data = [
                'sae_answer' => 2,
                'sae_answer_time' => $today
            ];
            if($user_type == 1){
                $data['sae_answer'] = 1;
            }
            Db::table('up_sae')->where('sae_id',$ff['sr_sae_id'])->update($data);
            try {
                $whoQ = Db::table('up_sae')->where('sae_id',$ff['sr_sae_id'])
                    ->field('sae_send_uid,sae_get_uid,sae_all_ids')->find();
                if($whoQ['sae_get_uid'] > 0){
                    $whoStr = $whoQ['sae_send_uid'] . $whoQ['sae_all_ids'];
                    $whoStr = trim($whoStr,',');
                    $whoArr = explode(',',$whoStr);
                    $list = array_diff($whoArr, array($user_id));
                    $this->Jpush(1, $list, '你有一条新的SAE报告回复消息，去处理', ['id' => $ff['sr_sae_id'],'n_type' => 3]);
                }
            } catch (\Exception $e) {
            }
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>100,'msg'=>'操作失败，请刷新重试']);
        }
    }

    /**
     * 已解决、已上报
     * type：1解决  2上报
     */
    public function saeOver()
    {
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type == 1){
            return json(['status'=>100,'msg'=>'您不能操作！']);
        }else{
            $today = date('Y-m-d H:i:s');
            if($type == 1){
                $data = [
                    'sae_answer' => 2,
                    'sae_answer_time' => $today
                ];
            }else{
                $data = [
                    'sae_submit' => 2,
                    'sae_submit_time' => $today
                ];
            }
            $res = Db::table('up_sae')->where('sae_id',$sae_id)->update($data);
            if($res){
                return json(['status'=>200,'msg'=>'操作成功']);
            }else{
                return json(['status'=>100,'msg'=>'操作失败，请刷新重试']);
            }
        }
    }
    /**
     * 转给同事
     */
    public function saeChangeUser()
    {
        extract(input());
        $user_type = $this->getUserInfo($user_id,'user_type');
        if($user_type == 1){
            return json(['status'=>100,'msg'=>'您无权转让']);
        }
        $sae = Db::table('up_sae')
            ->where('sae_id',$sae_id)
            ->field('sae_zhuan,sae_zhuan_ids,sae_all_ids')
            ->find();
        $today = date('Y-m-d H:i:s');
        $uids = trim($uids,',');
        $data = [
            'sae_all_ids' => $sae['sae_all_ids'] . $uids . ',',
            'sae_zhuan' => 2,
            'sae_update' => $today,
        ];
        if($sae['sae_zhuan'] == 1){
            $data['sae_zhuan_ids'] = ',' . $uids . ',';
        }else{
            $data['sae_zhuan_ids'] = $sae['sae_zhuan_ids'] . $uids . ',';
        }
        $res = Db::table('up_sae')->where('sae_id',$sae_id)->update($data);
        if($res){
            try {
                $list = explode(',',$uids);
                $this->Jpush(1, $list, '您有一个新的SAE报告内容转交给你进行协助处理', ['id' => $sae_id,'n_type' => 3]);
            } catch (\Exception $e) {
            }
            return json(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json(['status'=>100,'msg'=>'操作失败，请刷新重试']);
        }
    }
}